package com.cf.base.leak;

import android.app.Application;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.ScrollView;

import com.cf.base.leak.observe.ActivityLeak;
import com.cf.base.leak.observe.FragmentLeak;
import com.cf.base.leak.observe.MvpLeak;

import java.util.concurrent.TimeUnit;

/**
 * @author yangji
 */
public class Leak implements OnObjectLeakListener {

    private ObjectWatcher mObjectWatcher;
    private Application mApplication;
    private Handler mHandler;
    private static Leak instance = null;
    private static long outTime = TimeUnit.SECONDS.toMillis(5);

    static long getOutTime() {
        return outTime;
    }

    public static Leak getInstance() {
        if (instance == null) {
            synchronized (Leak.class) {
                if (instance == null) {
                    instance = new Leak();
                }
            }
        }
        return instance;
    }

    static void install(Application application) {
        getInstance().init(application);
    }

    private Leak() {
    }

    private void init(Application application) {
        this.mApplication = application;
        onCreate();
    }

    private void onCreate() {
        mHandler = new Handler(Looper.getMainLooper());
        mObjectWatcher = new ObjectWatcher(command ->
                mHandler.postDelayed(command,
                        (command instanceof LeakRunnable) ? ((LeakRunnable) command).getTime() : outTime));

        mObjectWatcher.addOnObjectLeakListeners(this);
        ActivityLeak.install(mApplication, mObjectWatcher);
        FragmentLeak.install(mApplication, mObjectWatcher);
        MvpLeak.install(mObjectWatcher);
    }

    public ObjectWatcher getWatcher() {
        return mObjectWatcher;
    }

    @Override
    public void objectLeak() {
        //内存泄漏了
    }
}
